package fun.shuofeng.juc.reentranlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionExample {
    static ReentrantLock lock = new ReentrantLock();
    static Condition waitCigaretteQueue = lock.newCondition();
    static Condition waitTakeoutQueue = lock.newCondition();
    static volatile boolean hasCigarette = false;
    static volatile boolean hasTakeout = false;


    public static void main(String[] args) throws InterruptedException {
        // 等烟
        new Thread(() -> {
            lock.lock();
            try {
                while (!hasCigarette) {
                    try {
                        waitCigaretteQueue.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t1 得到了香烟");
            } finally {
                lock.unlock();
            }
        }, "t1").start();
        // 等外卖
        new Thread(() -> {
            lock.lock();
            try {
                while (!hasTakeout) {
                    try {
                        waitTakeoutQueue.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 得到了外卖");
            } finally {
                lock.unlock();
            }
        }, "t2").start();

        TimeUnit.SECONDS.sleep(1);
        sendTakeout();
        TimeUnit.SECONDS.sleep(1);
        sendCigarette();

    }

    private static void sendCigarette() {
        lock.lock();
        try {
            System.out.println("送烟来了");
            hasCigarette = true;
            waitCigaretteQueue.signal();
        } finally {
            lock.unlock();
        }
    }

    private static void sendTakeout() {
        lock.lock();
        try {
            System.out.println("送早餐来了");
            hasTakeout = true;
            waitTakeoutQueue.signal();
        } finally {
            lock.unlock();
        }
    }
}
